package com.kuqi.controller;

import com.kuqi.Enumeration.ResponseCode;
import com.kuqi.Utils.Miscellaneous;
import com.kuqi.dao.UserRepository;
import com.kuqi.entity.UserInfo;
import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.sql.Date;
import java.util.Objects;


@Controller
public class UserController {

    @Autowired
    UserRepository userRepository;

    //根据applyKey和secretKey校验用户是否合法，账号是否过期
    @ResponseBody
    @RequestMapping(value = "/app/checkAccount.html", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String checkAccount(@RequestBody JSONObject jsonParam) {
        System.out.println(jsonParam.toJSONString());
        //获取参数并查询
        String applyKey = jsonParam.get("applyKey").toString();
        String secretKey = jsonParam.get("secretKey").toString();
        UserInfo user = userRepository.findByApplyKey(applyKey); // limit one
        JSONObject result = new JSONObject();
        if(user == null){ // 查询不到
            result.put("code", ResponseCode.NORESULT.getCode());
            result.put("msg",ResponseCode.NORESULT.getValue());
            result.put("data",null);
        }else if(!Objects.equals(user.getSecretKey(), secretKey)){ // 密码错误
            result.put("code",ResponseCode.SECRETERROR.getCode());
            result.put("msg",ResponseCode.SECRETERROR.getValue());
            result.put("data",null);
        }else if(Miscellaneous.checkPastDue(user.getRecordDate(),user.getEffective())){ // 账号过期
            result.put("code",ResponseCode.PASTDUE.getCode());
            result.put("msg",ResponseCode.PASTDUE.getValue());
            result.put("data",null);
        }else{
            result.put("code",ResponseCode.SUCCESS.getCode());
            result.put("msg",ResponseCode.SUCCESS.getValue());
            result.put("data",user.toJsonString());
        }
        return result.toJSONString();
    }


    // 用户注册一个全新的账号
    @ResponseBody
    @RequestMapping(value = "/app/registerUser.html", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String registerUser(@RequestBody JSONObject jsonParam) {
        System.out.println(jsonParam.toJSONString());
        //获取参数并注册
        String applyKey = jsonParam.get("applyKey").toString();
        String secretKey = jsonParam.get("secretKey").toString();
        UserInfo user = userRepository.findByApplyKey(applyKey);
        JSONObject result = new JSONObject();
        if(user != null){
            result.put("code",ResponseCode.REUSE.getCode());
            result.put("msg",ResponseCode.REUSE.getValue());
            result.put("data",null);
        }else{
            Date dateNow =  new Date(System.currentTimeMillis());
            int fixEffective = 3; // 新注册固定有效期只有三天
            int ageLimit = 1; // 默认开启未成年保护
            int res = userRepository.insertValue(applyKey, secretKey,ageLimit, dateNow, fixEffective, null);
            if(res > 0){
                result.put("code",ResponseCode.SUCCESS.getCode());
                result.put("msg",ResponseCode.SUCCESS.getValue());
                result.put("data",null);
            }else{
                result.put("code",ResponseCode.FAIL.getCode());
                result.put("msg",ResponseCode.FAIL.getValue());
                result.put("data",null);
            }
        }
        return result.toJSONString();
    }


    @ResponseBody
    @RequestMapping(value = "/app/registerUserWithImg.html", method = RequestMethod.POST, produces = "multipart/form-data;charset=UTF-8")
    public String registerUserWithImg(HttpServletRequest request) throws IOException {
        // 这里获取基础参数
        MultipartHttpServletRequest params=(MultipartHttpServletRequest) request;
        String applyKey = params.getParameter("applyKey");
        String secretKey = params.getParameter("secretKey");
        // 检查是否是重复注册
        UserInfo user = userRepository.findByApplyKey(applyKey);
        JSONObject result = new JSONObject();
        if(user != null){
            result.put("code", ResponseCode.REUSE.getCode());
            result.put("msg",ResponseCode.REUSE.getValue());
            result.put("data",null);
        }else{
            // 多个图片就用这个， 单个图片用下面这个
            // List<MultipartFile> files = params.getFiles("file");
            MultipartFile file = params.getFile("file");
            byte[] file_bytes = file.getBytes();
            Date dateNow =  new Date(System.currentTimeMillis());
            int fixEffective = 3; // 新注册固定有效期只有三天
            int ageLimit = 1; // 默认开启未成年保护
            int res = userRepository.insertValue(applyKey, secretKey,ageLimit, dateNow, fixEffective, file_bytes);
            if(res > 0){
                result.put("code",ResponseCode.SUCCESS.getCode());
                result.put("msg",ResponseCode.SUCCESS.getValue());
                result.put("data",null);
            }else{
                result.put("code",ResponseCode.FAIL.getCode());
                result.put("msg",ResponseCode.FAIL.getValue());
                result.put("data",null);
            }
        }
        return result.toJSONString();
    }


    @ResponseBody
    @RequestMapping(value = "/app/updateUserImg.html", method = RequestMethod.POST, produces = "multipart/form-data;charset=UTF-8")
    public String updateUserImg(HttpServletRequest request) throws IOException {
        // 这里获取基础参数
        MultipartHttpServletRequest params=(MultipartHttpServletRequest) request;
        String applyKey = params.getParameter("applyKey");
        MultipartFile file = params.getFile("file");
        byte[] file_bytes = file.getBytes();
        // 修改该用户的图标
        int res = userRepository.updateUserImg(applyKey, file_bytes);
        JSONObject result = new JSONObject();
        if(res > 0){
            result.put("code",ResponseCode.SUCCESS.getCode());
            result.put("msg",ResponseCode.SUCCESS.getValue());
            result.put("data",null);
        }else{
            result.put("code",ResponseCode.FAIL.getCode());
            result.put("msg",ResponseCode.FAIL.getValue());
            result.put("data",null);
        }
        return result.toJSONString();
    }
}